package com.tongda.menu.activity;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.WeakHashMap;
import org.springframework.http.ResponseEntity;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.tongda.core.common.KernalApplication;
import com.tongda.core.enums.StatusCodeEnum;
import com.tongda.core.service.TableService;
import com.tongda.core.utils.ActivityUtil;
import com.tongda.core.vo.DinerBill;
import com.tongda.core.vo.Employee;
import com.tongda.core.vo.MobileRspResult;
import com.tongda.core.vo.Table;
import com.tongda.menu.R;
import com.tongda.menu.widget.CustomEditText;
@SuppressLint("NewApi")
public class OpenTableActivity extends BaseActivity{
		
	private Table selectedTable;
	private CustomEditText peopleNumEdt;
	private Button confirmBtn;
	private int peopleNum;
	ResponseEntity<String> result = null;
	List<Table> tableList;
	protected DinerBill dinerBill;
	private TextView tableNoTv; 
	private List<Employee> employees;
	private Spinner salesSp;
	public ArrayAdapter<Employee> spAdapter;
	private Employee currentEmployee;
	private KernalApplication application;
	private ImageView openCloseImv;
	private String dinnerStatus;
	private String order="no";
	private String cartEdit;
	private String billId;
	
	Handler handler = new Handler(){

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			Intent intent = null;
			switch(msg.what){
			case 2:
				ActivityUtil.Toast(OpenTableActivity.this, "网络原因导致餐台信息修改失败,请尝试重新修改", false, false);
				OpenTableActivity.this.finish();
				application.setMenuMainIsRefresh(true);
				intent = new Intent(OpenTableActivity.this,CartActivity.class);
				break;
			case 3:
				application.getMenuSelectedTable().setPeopleCount(peopleNum);
				OpenTableActivity.this.finish();
				application.setMenuMainIsRefresh(true);
				intent = new Intent(OpenTableActivity.this,CartActivity.class);
				break;
			case 0:
				 Toast.makeText(OpenTableActivity.this, "开台失败,请重新点击开台", Toast.LENGTH_SHORT).show();
				break;
			case 1:
				String billId = msg.getData().getString("billId");
        		selectedTable.setBillId(billId);
				application.setMenuSelectedTable(selectedTable);
	    	    application.getMenuSelectedTable().setPeopleCount(peopleNum);
				application.setMenuMainIsRefresh(true);
        		OpenTableActivity.this.finish();
    			 intent  = new Intent(OpenTableActivity.this,CartActivity.class);
    			 intent.putExtra("order", order);
				break;
				default:
					break;
			}
			if(intent!=null){
				startActivity(intent);
				overridePendingTransition(R.anim.in_from_bottom, R.anim.out_to_top);
			}
		}
		
	};
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		application = KernalApplication.getInstance();
		Intent intent = getIntent();
		selectedTable = (Table) intent.getSerializableExtra("table");
		dinnerStatus = intent.getStringExtra("dinnerStatus");
		order = intent.getStringExtra("order");
		cartEdit = intent.getStringExtra("cartEdit");
		billId = intent.getStringExtra("billId");
		
		setContentView(R.layout.activity_opentable);
		tableNoTv = (TextView)findViewById(R.id.open_tableNo);
		peopleNumEdt = (CustomEditText)findViewById(R.id.open_peoplenum);
		confirmBtn = (Button)findViewById(R.id.open_confirm);
		openCloseImv = (ImageView)findViewById(R.id.open_close);
		salesSp = (Spinner)findViewById(R.id.open_salemanSp);
		salesSp.setPrompt("请选择营销员");
		peopleNumEdt.changeMaxNum(application.getMenuSelectedTable().getSeat());
		if(dinnerStatus.equals("1")){
			tableNoTv.setText(selectedTable.getTabNo());
		}else if(dinnerStatus.equals("2")){
			tableNoTv.setText(application.getMenuSelectedTable().getTabNo());
		}
	
		if(dinnerStatus.equals("2") && cartEdit!=null && cartEdit.equals("cartEdit")){
			peopleNumEdt.Custv.setText(application.getMenuSelectedTable().getPeopleCount()+"");
			peopleNumEdt.changeNum(Integer.valueOf(application.getMenuSelectedTable().getPeopleCount()));
		}
		employees = new ArrayList<Employee>();
		new GetSaleManTask().execute();
		
		confirmBtn.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				
				peopleNum = Integer.valueOf(peopleNumEdt.Custv.getText()+"");
				int people_count_i =Integer.valueOf(peopleNum);
				
				if(dinnerStatus.equals("1")){
					dinerBill = new DinerBill();
					dinerBill.setBillTime(new Date());
//2.2.0				dinerBill.setCreateEmployee(getCurrentUser());
//					dinerBill.setWaiterName(getCurrentUser().getName());
					dinerBill.setPeopleNum(people_count_i);
					dinerBill.setTabNo(selectedTable.getTabNo());
					dinerBill.setTable(selectedTable);
					if(currentEmployee!=null){
						dinerBill.setSalesmanId(currentEmployee.getEmpId());
						dinerBill.setSalesmanName(currentEmployee.getName());
					}
					
					  Thread openThread = new Thread(new Runnable() {
						
						@Override
						public void run() {
							MobileRspResult result = TableService.openTable(dinerBill);
							Message msg = handler.obtainMessage();
							//不需要弹出是否清空的提示框
				        	if(StatusCodeEnum.SUCCESS.getCode().equals(result.getStatusCode())){
				        		msg.what=1;
				        		String billId = (String) result.getObject();
								Bundle data = new Bundle();
								data.putString("billId", billId);
								msg.setData(data);
				    	     }else{
				    	    	 msg.what=0;
				    	     }
				        	handler.sendMessage(msg);
						}
					});
					  openThread.start();
				}else if(dinnerStatus.equals("2") && cartEdit!=null && cartEdit.equals("cartEdit")){
					
    				dinerBill = new DinerBill();
//2.2.0					dinerBill.setWaiterName(getCurrentUser().getName());
					dinerBill.setPeopleNum(people_count_i);
					dinerBill.setTabNo(application.getMenuSelectedTable().getTabNo());
					dinerBill.setTable(application.getMenuSelectedTable());
					if(currentEmployee!=null){
						dinerBill.setSalesmanId(currentEmployee.getEmpId());
						dinerBill.setSalesmanName(currentEmployee.getName());
					}
					dinerBill.setOldTabId(application.getMenuSelectedTable().getTabId());
					dinerBill.setBillId(billId);
					
    				//修改餐台信息
    				Thread updateTable = new Thread(new Runnable() {
						@Override
						public void run() {
							MobileRspResult result = TableService.openTableUpdate(dinerBill);
							Message msg = handler.obtainMessage();
							if(StatusCodeEnum.SUCCESS.getCode().equals(result.getStatusCode())){
								msg.what=3;
							}else{
								msg.what=2;
							}
							handler.sendMessage(msg);
						}
					});
    				updateTable.start();
				}
				
			}
		});
		openCloseImv.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				OpenTableActivity.this.finish();
			}
		});
	}
	
	
	public class GetSaleManTask extends AsyncTask<Void, Void, List<Employee>>{

		@Override
		protected List<Employee> doInBackground(Void... params) {
			employees = TableService.getSalesMan();
			 ArrayList<Employee> emList=new ArrayList<Employee>();
			 Employee tempEmp=new Employee();
			 tempEmp.setName("请选择");
			 emList.add(tempEmp);
			 if(employees!=null){
				 emList.addAll(employees);
			 }
			 employees=emList;
			return employees;
		}
		
		@Override
		protected void onPostExecute(List<Employee> result) {
			super.onPostExecute(result);
			if(employees!=null){
				spAdapter = new ArrayAdapter<Employee>(OpenTableActivity.this, android.R.layout.simple_spinner_item, employees);
				spAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
				salesSp.setAdapter(spAdapter);
				
				salesSp.setOnItemSelectedListener(new OnItemSelectedListener() {
 
					@Override
					public void onItemSelected(AdapterView<?> parent, View view,
							int position, long id) {
						if(position!=0){
							currentEmployee = employees.get(position);
						}
					}

					@Override
					public void onNothingSelected(AdapterView<?> parent) {
						
					}
				});
			}
			

		}
	}
}
